// pages/cart/index.js
import myRequest from '../../utils/net.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: null,
    detailAddress: '',
    cartList: [],
    isAll: false,
    totalPrice: 0
  },
  generateGoods: function () {
    // 生成订单参数数据
    let list = [];
    let cart = wx.getStorageSync('mycart');
    for (let key in cart) {
      let p = cart[key];
      if (p.checked) {
        // 选中商品
        let item = {};
        item.goods_id = p.goods_id;
        item.goods_number = p.num;
        item.goods_price = p.goods_price;
        list.push(item);
      }
    }
    return list;
  },

  toPay: function () {
    // 去付款
    // 1、如果用户没有选中商品，提示一下，终止后续操作
    let flag = false;
    let cart = wx.getStorageSync('mycart');
    for (let key in cart) {
      if (cart[key].checked) {
        // 包含选中商品
        flag = true;
        break;
      }
    }
    if (!flag) {
      // 没有选中商品
      wx.showToast({
        title: '请求选择商品...',
      });
      return;
    }
    // 要想进行支付，需要先登录，如果登录成功后，服务器会返回一个token，客户端收到token后会保存在本地缓存中
    // wx.setStorageSync('mytoken', res.token);
    // 2. 先判断用户是否已经登录
    let token = wx.getStorageSync('mytoken');
    if (!token) {
      // 没有登录，跳转到登录授权页面
      wx.navigateTo({
        url: '/pages/auth/index',
      })
    }
    // 3、需要生成订单
    // 准备订单相关参数
    let param = {
      order_price: this.data.totalPrice,
      consignee_addr: this.data.detailAddress,
      goods: this.generateGoods()
    }
    // 调用后台接口实现订单创建
    myRequest('my/orders/create', param, 'post', {
      Authorization: token
    }).then(res => {
      console.log(res);
      //个人账号无法生成订单，模拟
      // let orderNumber = res.data.message.order_number;
      let orderNumber = 12345678
      //将订单号传递到订单确认页面
      wx.navigateTo({
        url: '/pages/order/index?orderNumber=' + orderNumber,
        success: (result) => {

        },
        fail: () => {},
        complete: () => {}
      });

    });
  },

  handleSub: function (e) {
    let gid = e.target.dataset.id;
    let cart = wx.getStorageSync('mycart')
    console.log(cart)
    let num = cart[gid].num;
    if (num > 1) {
      cart[gid].num = num - 1;
    }
    // 计算总价
    console.log(cart)
    let totalPrice = this.data.totalPrice
    if (cart[gid].checked) {
      totalPrice = totalPrice - cart[gid].goods_price;
    }
    console.log(cart)
    // 更新页面数据
    this.setData({
      cartList: cart,
      totalPrice: totalPrice
    })
    wx.setStorageSync('mycart', cart);
  },

  handleAdd: function (e) {
    let gid = e.target.dataset.id;
    let cart = wx.getStorageSync('mycart')
    cart[gid].num++;
    let totalPrice = this.data.totalPrice
    if (cart[gid].checked) {
      totalPrice = totalPrice + cart[gid].goods_price;
    }

    this.setData({
      cartList: cart,
      totalPrice: totalPrice
    })
    wx.setStorageSync('mycart', cart);
  },

  toggleItem: function (e) {
    let gid = e.target.dataset.id;
    let cart = wx.getStorageSync('mycart')
    cart[gid].checked = !cart[gid].checked
    let price = cart[gid].goods_price * cart[gid].num;
    let totalPrice = cart[gid].checked ? 0 + price : 0 - price;
    this.setData({
      totalPrice: this.data.totalPrice + totalPrice
    })
    wx.setStorageSync('mycart', cart);
  },

  toggleAll: function (e) {
    let cart = wx.getStorageSync('mycart')
    let totalPrice = 0
    for (let key in cart) {
      cart[key].checked = !this.data.isAll;
      if (cart[key].checked) {
        totalPrice += cart[key].goods_price * cart[key].num;
      }
    }
    this.setData({
      cartList: cart,
      isAll: !this.data.isAll,
      totalPrice: totalPrice
    })
    wx.setStorageSync('mycart', cart);
  },

  loadCartData: function () {
    let res = wx.getStorageSync('myAddress');
    if (res) {
      this.setData({
        address: res,
        detailAddress: `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}`
      });
    }

    // 从本地缓存获取购物车数据并进行加工处理
    // { 1232： {}， 1212：{}}
    let cart = wx.getStorageSync('mycart');
    // 判断是否全都选中
    //计算总价
    let flag = true;
    let totalPrice = 0;
    for (let key in cart) {
      flag &= cart[key].checked
      if (cart[key].checked) {
        totalPrice += cart[key].goods_price * cart[key].num;
      }
    }
    // 把对象转化为数组
    // let list = [];
    // for (let key in cart) {
    //   // 其中一件商品信息
    //   let prod = cart[key];
    //   list.push(prod);
    // }
    // // 初始化data中的数据列表
    // this.setData({
    //   cartList: list
    // });
    this.setData({
      cartList: cart,
      isAll: flag,
      totalPrice: totalPrice
    });
  },

  handleAddress: function () {
    // 获取收货地址
    wx.chooseAddress({
      success: (res) => {
        console.log(res)
        // 把收货地址进行缓存
        wx.setStorageSync('myAddress', res);
        this.setData({
          address: res,
          detailAddress: `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}`
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onload")
    // this.loadCartData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("onready")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("onshow")
    this.loadCartData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("onhide")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("onunload")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})